/* ====================================== toast  ====================================== */
import React from 'react'
// ===================================================================== TimePicker
import { TimePicker } from 'antd'
import $time from '@utils/moment'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
// ===================================================================== declare
const { $fn } = window
// ===================================================================== TimePicker
class Index extends React.Component{
	state = {}
	
	onChange = value => {
		const { onChange, onChanged, name, outer } = this.props
		const $format = value => $time.format(value, { t: 'hms' }) 	// 将时间格式化为字符串
		
		let model = null
		
		if(!outer){ this.setState({ value }) }
		
		let time = $format(value)
		model = name ? { [name]: time } : time
		onChanged?.({ model, value: time, name })
		onChange?.(time)
	}
	
	setValue = value =>  this.setState({ value: value})
	
	clear = () => this.setState({ value: '' })
	
	onBefore = (before, index) => {
		let stack = []
		if($fn.hasArray(before)){
			let t = +before[index]
			for(var i=0; i<t; i++){
				stack.push(i)
			}
		}
		return stack
	}
	
	onAfter = (after, index) => {
		let stack = []
		if($fn.hasArray(after)){
			const s = [ 23, 59, 59 ]
			let t = +after[index]
			for(var i=s[index]; i>t; i--){
				stack.push(i)
			}
		}
		return stack
	}
	
	
	render(){
		let { width, size,  className, p, disabled, value, bordered, after, before } = this.props
		let _value = this.state.value === undefined ? value : this.state.value
		
		_value = _value && value !== '--' ? moment(_value, 'HH:mm:ss') : null
		
		if(after){
			after = after.split(':')
		}
		if(before){
			before = before.split(':')
		}
		
		return (
			<TimePicker 
				value		= { _value } 
				size		= { size || 'small' } 
				onChange	= { this.onChange }
				style		= {{ width }} 
				className 	= {`${className?className:''} ${bordered===false ? 'input-bordered':''}`}
				placeholder = { p } 
				disabled 	= { disabled }
				bordered	= { bordered }
				hideDisabledOptions	= { true }
				disabledTime = {() => {
					return {
						disabledHours: () => {
							if(after){
								return this.onAfter(after,0)
							}else if(before){
								return this.onBefore(before,0)
							}
						},
						disabledMinutes: () => {
							if(after){
								return this.onAfter(after,1)
							}else if(before){
								return this.onBefore(before,1)
							}
						},
						disabledSeconds: () => {
							if(after){
								return this.onAfter(after,2)
							}else if(before){
								return this.onBefore(before,2)
							}
						}
					}
				}}
			/>
		)
	}
}

export default Index